package cn.touna.jss.modules.custom.batch;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CsvWriter {

    private File dest;
    private CsvWriterConfig config;

    private BufferedWriter bw = null;
    public CsvWriter(File dest,CsvWriterConfig config){
        this.dest = dest;
        this.config = config;
    }

    public synchronized void write(JSONObject row) throws IOException {
        int last = config.getColumns().size() - 1;
        if(bw == null){
            bw = new BufferedWriter(new FileWriter(dest));
            if(config.isExportHeaders()){
                for(int i = 0;i<config.getColumns().size();i++){
                    bw.append(config.getColumns().get(i));
                    if(last == i){
                        bw.append("\r\n");
                    }else{
                        bw.append(config.getSeperator());
                    }
                }

            }
        }

        for(int i = 0;i<config.getColumns().size();i++){
            String name = config.getColumns().get(i);
            String value = row.getString(name);
            if(value == null){
                if(config.getNullReplacement() != null){
                    value = config.getNullReplacement();
                }else
                    value = "null";
            }
            bw.append(value);
            if(last == i){
                bw.append("\r\n");
            }else{
                bw.append(config.getSeperator());
            }
        }
        bw.flush();
    }

    public synchronized void close(){
        if(bw==null)
            return;
        try {
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public CsvWriterConfig getConfig() {
        return config;
    }




}
